package com.i2works.smartluolong.utils.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.google.common.collect.Lists;
import com.i2works.smartluolong.utils.base.DateConstant;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;

import java.nio.charset.Charset;
import java.util.List;

/**
 * fastjson
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/1/18 13:22
 */

public class FastjsonConfigurationUtils {

    /**
     * 使用@Bean注入fastJsonHttpMessageConvert
     */
    public static HttpMessageConverters fastJsonHttpMessageConverters() {
        //1.需要定义一个Convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2.添加fastjson的配置信息，比如是否要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue,SerializerFeature.SortField);
        fastJsonConfig.setDateFormat(DateConstant.ALL);
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        //3.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //4.处理中文乱码问题
        List<MediaType> fastMediaTypes = Lists.newArrayList();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        return new HttpMessageConverters(fastConverter);
    }

    /**
     * 处理请求时返回json字符串的中文乱码问题
     */
    public static StringHttpMessageConverter stringHttpMessageConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter();
        List<MediaType> mediaTypeList = Lists.newArrayList(new MediaType("application/json;charset=UTF-8"), new MediaType("text/html;charset=UTF-8"), new MediaType("text/json;charset=UTF-8"));
        converter.setSupportedMediaTypes(mediaTypeList);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        return converter;
    }

}
